package com.bite.common.security.service;

import cn.hutool.core.lang.UUID;
import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.constants.JwtConstants;
import com.bite.common.core.enums.LoginUserIdentity;
import com.bite.common.redis.service.RedisService;
import com.bite.common.core.domain.LoginUser;
import com.bite.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;


    public String createTokenAndRedisDTS(Map<String, Object> claims, String jwtSecret,
                                         LoginUserIdentity loginUserIdentity) {
        // 一、返回一个token给用户
        // 返回给用户的token中payload包含两部分，
        // 一是用户的userId（数据库主键），二是userKey，这是redis的key的唯一标识
        if (!claims.containsKey(JwtConstants.LOGIN_USER_KEY)){
            String userKey = UUID.fastUUID().toString();
            claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        }
        redisDTS((String)claims.get(JwtConstants.LOGIN_USER_KEY), loginUserIdentity);
        return JwtUtils.createToken(claims, jwtSecret);
    }

    //redis同步数据
    private void redisDTS(String userKey, LoginUserIdentity loginUserIdentity) {
        // 二、redis内同步更新用户信息
        // redis中的key：loginToken:uuid
        String key = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        // redis中的value，即LoginUser，目前内部仅存储一个Integer权限
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(loginUserIdentity.getValue());
        redisService.setCacheObject(key, loginUser, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
    }

    public void extendToken(String token, String jwtSecret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, jwtSecret);
            if (claims == null){
                log.error("解析token: {}, 出现异常",  token);
                return;
            }
        } catch (Exception e) {
            log.error("解析token出现异常, ", e);
            return;
        }
        String userKey = claims.get(JwtConstants.LOGIN_USER_KEY).toString();
        if (userKey == null){
            userKey = "";
        }
        String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire <= CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
        }
    }


}
